﻿using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;

public class ScreenShotWindow : ScriptableWizard {

	static int width;
	static int height;
	static int cameraHeight;
	
	[MenuItem("Tools/Screen Shot")]
	static void Init()
	{
		ScreenShotWindow window = (ScreenShotWindow)EditorWindow.GetWindow(typeof(ScreenShotWindow));
		cameraHeight = 200;
		PlayerPrefs.SetInt("defaultScreenWidth", PlayerSettings.defaultScreenWidth);
		PlayerPrefs.SetInt("defaultScreenHeight", PlayerSettings.defaultScreenHeight);
		
		width = 800;
		height = 480;
	}
	
	void OnGUI()
	{
		EditorGUIUtility.LookLikeControls(160f);
		EditorGUILayout.Space();
		
		EditorGUILayout.PrefixLabel("Set Screen Size:");
		EditorGUILayout.BeginHorizontal();
		width = EditorGUILayout.IntField("Width:", width);
		height = EditorGUILayout.IntField("Height", height);
		EditorGUILayout.EndHorizontal();
		
		EditorGUILayout.Space();
		
		EditorGUILayout.PrefixLabel("Set Camera Height:");
		cameraHeight = EditorGUILayout.IntField("Camera Height:", cameraHeight);
		
		EditorGUILayout.Space();
		if(GUILayout.Button("截屏", GUILayout.Height(30)))
		{
			ScreenShotNow();
		}
		if(GUILayout.Button("恢复场景设置", GUILayout.Height(30)))
		{
			Revert();
		}
	}
	
	void ScreenShotNow()
	{
		Terrain terrain = Terrain.activeTerrain;
		Transform terrainTrans = terrain.transform;
		Vector2 terrainSize = terrainTrans.localScale;
		
		GameObject caObj = GameObject.Find("ShotCamera");
		if(caObj == null)
			caObj = new GameObject("ShotCamera", typeof(Camera));
		
		Camera ca = caObj.GetComponent<Camera>();
		ca.isOrthoGraphic = true;
		ca.depth = 1000;
		Transform caTrans = ca.transform;
		caTrans.localRotation = Quaternion.Euler(90, 0, 0);
		ca.orthographicSize = Mathf.Max(terrainSize.x, terrainSize.y) * 5f;
		caTrans.position = terrainTrans.position + new Vector3(ca.orthographicSize, cameraHeight, ca.orthographicSize);
		string screenShotFolder = Directory.GetCurrentDirectory() + "/ScreenShot/";
		if(!Directory.Exists(screenShotFolder))
			Directory.CreateDirectory(screenShotFolder);
		
		PlayerSettings.defaultScreenWidth = width;
		PlayerSettings.defaultScreenHeight = height;
		
		string currentScene = EditorApplication.currentScene;
		string sceneName = Path.GetFileNameWithoutExtension(currentScene);
		string timeTag = System.DateTime.Now.ToString().Replace('/', '_');
		timeTag = timeTag.Replace(':', '_');
		string filePath = screenShotFolder + sceneName + "_" + timeTag + ".png";
		
		Application.CaptureScreenshot(filePath);
	}
	
	static void Revert()
	{
		GameObject caObj = GameObject.Find("ShotCamera");
		if(caObj == null)
			DestroyImmediate(caObj);
		
		PlayerSettings.defaultScreenWidth = PlayerPrefs.GetInt("defaultScreenWidth");
		PlayerSettings.defaultScreenHeight = PlayerPrefs.GetInt("defaultScreenHeight");
	}
}
